package com.css.apps.base.user.action;

import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.base.org.model.SOrg;
import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.user.leader.model.LeaderSecretary;
import com.css.apps.base.user.model.SUser;
import com.css.apps.base.user.service.UserHelper;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.ids.server.service.IdsService;
import com.css.util.Ajax;
import com.css.util.Json;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ModelDriven;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("serial")
public class UpdUser extends AdminAction implements ModelDriven {
	
	private static Log log = LogFactory.getLog(UpdUser.class);
	private SUser item;
	private String orgIds, secretaryJson;

	public UpdUser() {
		this.item = new SUser();
	}

	@SuppressWarnings("unchecked")
	protected String adminGo() {
		TransactionCache tx = null;
		try {
			String userId = item.getUuid();
			Object uuid = new QueryCache("select a.uuid from SUser a where a.uuid=:uuid").setParameter("uuid", userId)
					.setMaxResults(1).uniqueResult();// 此处不能有缓存
			if (uuid == null) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.userNotExist"));
				return Action.ERROR;
			}
			// 用户所属的所有部门id
			List<String> orgIdList = StringHelper.strToList(orgIds);
			// 将第一个部门id加入SUser表中的orgId字段
			item.setOrgId(orgIdList.get(0));
			if (StringHelper.isEmpty(item.getLoginName()) || StringHelper.isEmpty(item.getRealName())
					|| StringHelper.isEmpty(item.getOrgId())) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}

			Object id = new QueryCache("select a.uuid from SUser a where a.loginName=:loginName and a.uuid!=:uuid and a.delFlag='2'")
							.setParameter("loginName", item.getLoginName()).setParameter("uuid", userId)
							.setMaxResults(1).uniqueResult();// 此处不能有缓存
			if (id != null) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR,
						Messages.getString("sysmgrMsg.loginnameExsit", new String[] { item.getLoginName() }));
				return Action.ERROR;
			}

			SUser tmp = QueryCache.get(SUser.class, userId);
			tmp.setUuid(item.getUuid());
			tmp.setRealName(item.getRealName());
			tmp.setLoginName(item.getLoginName());
			tmp.setSex(item.getSex());
			tmp.setMobile(item.getMobile());
			tmp.setPhone(item.getPhone());
			tmp.setEmail(item.getEmail());
			tmp.setUserType(item.getUserType());
			tmp.setOrderNum(item.getOrderNum());
			tmp.setRoomNum(item.getRoomNum());
			tmp.setEditDate(new Date());
			tmp.setRemark(item.getRemark());
			tmp.setOrgId(item.getOrgId());
			tmp.setSecLevel(item.getSecLevel());
			tmp.setJob(item.getJob());
			
			List<Object> delList = null;
			UserHelper helper = new UserHelper();
			if (StringHelper.isNotEmpty(secretaryJson)) {
				 delList = new QueryCache("from LeaderSecretary where leaderId = :leaderId")
						.setParameter("leaderId", userId).list();
			}
			
			List<LeaderSecretary> lsList = helper.getLeaderSecretary(userId, secretaryJson);
			
			tx = new TransactionCache();
			tx.delete(delList);
			tx.update(tmp);
			tx.save(lsList);
			// 对于org的处理
			// 先将原有部门-用户关联纪录删除，再添加
			StringBuffer sd = new StringBuffer("delete from SUserOrg a where a.userId=:userId");
			Map<String, Object> params = new HashMap<>();
			params.put("userId", userId);
			tx.executeUpdate(sd.toString(), params);
			tmp.getOrgList().removeAll();
			// 添加现有部门-用户关联
			for (String orgId : orgIdList) {
				SUserOrg userorg = new SUserOrg();
				userorg.setDeptId(orgId.trim());
				userorg.setUserId(item.getUuid());
				SOrg corp = getCorp(orgId);
				userorg.setOrgId(corp.getUuid());
				tx.save(userorg);
				tmp.getOrgList().add(orgId.trim());
			}

			tx.commit();

			LogPart lp = new LogPart();
			lp.setOpObjType(SUser.class.getName());
			lp.setOpObjId(item.getUuid());
			lp.setRelObjType(SUser.class.getName());
			lp.setRelObjId(item.getUuid());
			lp.setOpType(LogConstant.LOG_TYPE_MODIFY);
			lp.setLogLevel(LogConstant.LOG_LEVEL_COMMON);
			lp.setLogData(Json.object2json(tmp));
			lp.setResult(LogConstant.RESULT_SUCCESS);
			lp.save();

			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"), tmp.getUuid());
			return Action.SUCCESS;
		} catch (Exception ex) {
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	private SOrg getCorp(String orgId) {
		if (StringHelper.isEmpty(orgId)) {
			return null;
		}
		SOrg parent = QueryCache.get(SOrg.class, orgId);
		if (IdsService.ORG_ORG_TYPE.equals(parent.getOrgType())) {
			return parent;
		} else {
			return getCorp(parent.getParentId());
		}
	}
	
	public SUser getModel() {
		return item;
	}

	public SUser getUser() {
		return item;
	}

	public void setUser(SUser user) {
		this.item = user;
	}

	public SUser getItem() {
		return item;
	}

	public void setItem(SUser item) {
		this.item = item;
	}

	public String getOrgIds() {
		return orgIds;
	}

	public void setOrgIds(String orgIds) {
		this.orgIds = orgIds;
	}

	public String getSecretaryJson() {
		return secretaryJson;
	}

	public void setSecretaryJson(String secretaryJson) {
		this.secretaryJson = secretaryJson;
	}

}
